package com.fy.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet("/chat/loadMsg")
public class LoadMsgServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public Map<String, String> msgs = new HashMap<String, String>();
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String action = request.getParameter("action");
		HttpSession session = request.getSession();
		if ("login".equals(action)) {
			String username = request.getParameter("username");
			// String password = request.getParameter("password");
			session.setAttribute("username", username);
			String msg = "欢迎" + username + " 光临聊天室！<br />";
			msgs.put(username, msg);
			response.sendRedirect("index.html");
		}
		if ("write".equals(action)) {
			String newMsg = request.getParameter("msg");
			String nm = session.getAttribute("username") + ": " + newMsg;
			// out.print("聊天记录："+nm);
			// 发消息时，将所有聊天室的里边聊天记录进行叠加
			Iterator<String> it = msgs.keySet().iterator();
			String username = null;
			String msg = null;
			while (it.hasNext()) {
				username = it.next(); // 用户名
				msg = msgs.get(username); // 消息
				msg = msg + "<br />" + nm;
				msgs.put(username, msg);
			}
			response.sendRedirect("writerMsg.jsp");
		}
		if ("show".equals(action)) {
			// 显示用的聊天记录
			String username = (String) session.getAttribute("username");
			String msg = msgs.get(username);
			PrintWriter out = response.getWriter();
			out.println("loadData.innerHTML=\"" + msg + "\";");
		}
	}
}